import urllib.parse
import web
from utils.WXBizMsgCrypt3 import WXBizMsgCrypt
import xml.etree.ElementTree as ET
import os,sys,asyncio
from utils.EdgeGptOperator import EdgeGptanswer
from utils.wechart import wechat
from utils.Continuous import edgeGptOperator
import requests

class Handle(object):
    sToken = os.getenv("sToken")
    sEncodingAESKey = os.getenv("sEncodingAESKey")
    sCorpID = os.getenv("CORPID")
     
    #回调验证接口
    def GET(self):  
        try:
            data = web.input()
            if len(data) == 0:
                return "no data"
            sVerifyMsgSig = data.msg_signature
            sVerifyTimeStamp = data.timestamp
            sVerifyNonce = data.nonce
            sVerifyEchoStr = data.echostr
            if sVerifyEchoStr is not None:
                wxcpt=WXBizMsgCrypt(self.sToken,self.sEncodingAESKey,self.sCorpID)
                ret,sEchoStr=wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,sVerifyNonce,sVerifyEchoStr)
                if(ret!=0):
                    print("ERR: VerifyURL ret: " + str(ret))
                    sys.exit(1)
                else:
                    print("done VerifyURL")
                    return sEchoStr
         
        except Exception as Argument:
            print(Argument)
    #回调API调用是post
    def POST(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "no data"
            sReqMsgSig = data.msg_signature
            sReqTimeStamp = data.timestamp
            sReqNonce = data.nonce
            sReqData = web.data()
            if len(sReqData) == 0:
                return "hello, this is handle view"
            wxcpt=WXBizMsgCrypt(self.sToken,self.sEncodingAESKey,self.sCorpID)
            ret,sMsg=wxcpt.DecryptMsg( sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce)
            if( ret!=0 ):
                print("ERR: DecryptMsg ret: " + str(ret))
                sys.exit(1)
            xml_tree = ET.fromstring(sMsg)
            content = xml_tree.find("Content").text
            #content为微信实际接收的消息
            print("接收的消息：" +content)
            wxcpt=WXBizMsgCrypt(self.sToken,self.sEncodingAESKey,self.sCorpID)
            ToUserName = xml_tree.find("ToUserName").text
            CreateTime = xml_tree.find("CreateTime").text
            FromUserName = xml_tree.find("FromUserName").text
            MsgType = xml_tree.find("MsgType").text
            AgentID = xml_tree.find("AgentID").text
            # content=return_text
            # Event = xml_tree.find("Event").text
            # EventKey = xml_tree.find("EventKey").text
            # content = '接口获取失败'
            # if MsgType=='event' and Event=='click':
            #     if EventKey == '自定义菜单的健值1':
            #         #你自己的数据处理
            #         content =  "你要返回的处理内容"
            #     if EventKey == '自定义菜单的健值2':
            #         #你自己的数据处理
            #         content =  "你要返回的处理内容"
            sendContent = urllib.parse.quote(content)
            try:
                requests.get("http://127.0.0.1:9999/continuousEdgeGpt?content=" + sendContent ,timeout=0.0000000001)
            except requests.exceptions.ReadTimeout: 
                pass
            reData=""
            sRespData = "<xml><ToUserName>"+ToUserName+"</ToUserName><FromUserName>"+FromUserName+"</FromUserName><CreateTime>"+CreateTime+"</CreateTime><MsgType>text</MsgType><Content>"+reData+"</Content><AgentID>"+AgentID+"</AgentID></xml>"
            ret,sEncryptMsg=wxcpt.EncryptMsg(sRespData, sReqNonce, sReqTimeStamp)
            if( ret!=0 ):
                print ("ERR: EncryptMsg ret: " + str(ret))
                sys.exit(1)
            return sEncryptMsg      
        except Exception as Argument:
            print(Argument)
            return(Argument)   
        # finally:
        #     question(content)

# 测试非连续对话
class ApiTest(object):
    def GET(self):  
        data = web.input()
        print(data.content)
        text = data.content
        wechat.send_text_message("返回数据：" + text) 
        return "get"
    def POST(self):
        print("post")
        return "post"
    
# 测试连续对话,输入重置时，重置会话
class ContinuousApiTest(object):
    def GET(self):  
        data = web.input()
        if data.content == "重置":
            print("重置会话")
            asyncio.run(edgeGptOperator.resetBot())
        else:
            print("问题：" + data.content)
            text = asyncio.run(edgeGptOperator.bingAnswerSend(data.content))
            wechat.send_text_message("返回数据：" + text) 
        return "get"
    def POST(self):
        print("post")
        return "post"

# 非连续对话接口
class EdgeGpt(object):
    def GET(self):  
        data = web.input()
        print("问题：" + data.content)
        answer = EdgeGptanswer(data.content)
        wechat.send_text_message(answer) 
        return "get"
    def POST(self):
        print("post")
        return "post"

# 连续对话接口
class ContinuousEdgeGpt(object):
    def GET(self):  
        data = web.input()
        if data.content == "重置":
            print("重置会话")
            asyncio.run(edgeGptOperator.resetBot())
        else:
            print("问题：" + data.content)
            asyncio.run(edgeGptOperator.bingAnswerSend(data.content))
        return "get"
    def POST(self):
        print("post")
        return "post"